//
//  XS_Observable.swift
//  Pods
//
//  Created by 韩云智 on 2019/10/8.
//  Copyright © 2019 韩云智. All rights reserved.
//

import HandyJSON
import RxSwift

//数据映射错误
public enum RxMapModelError: Error {
    case parsingError
}

//扩展Observable：增加模型映射方法
public extension Observable where Element:Any {
    //将JSON数据转成对象
    open func mapResponse<T>(type:T.Type) -> Observable<T> where T:HandyJSON {
        return self.map { (element) -> T in
            guard let parsedElement = T.deserialize(from: element as? Dictionary) else {
//                throw RxMapModelError.parsingError
                return T.init()
            }
            return parsedElement
        }
    }
}

/// Json模型映射导出数据模型
public extension Observable where Element: XS_Response {
    //将JSON数据转成对象
    open func mapModel<T>(type:T.Type) -> Observable<(T?, XS_Response)> where T:HandyJSON {
        return self.map { (element) -> (T?, XS_Response) in
//            guard let parsedElement = T.deserialize(from: element.data as? Dictionary) else {
//                throw RxMapModelError.parsingError
//            }
            let parsedElement = T.deserialize(from: element.data as? Dictionary)
            return (parsedElement, element)
        }
    }
    
    //将JSON数据转成数组
    open func mapModels<T>(type:T.Type) -> Observable<([T], XS_Response)> where T:HandyJSON {
        return self.map { (element) -> ([T], XS_Response) in
            guard let parsedArray = [T].deserialize(from: element.data as? [Any]) as? [T] else {
//                throw RxMapModelError.parsingError
                return ([], element)
            }
            return (parsedArray, element)
        }
    }
}
